/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vistas.crear;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import persistencia.Cobros;
import persistencia.Factura;

/**
 *
 * @author hellwolf
 */
public class crearCobro extends javax.swing.JFrame {

    /**
     * Creates new form crearCobro
     */
    public crearCobro() {
        initComponents();
        centrarVentana();
    }

    private void centrarVentana() {
        // Se obtienen las dimensiones en pixels de la pantalla.
        Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();
        // Se obtienen las dimensiones en pixels de la ventana.
        Dimension ventana = getSize();
        // Una cuenta para situar la ventana en el centro de la pantalla.
        setLocation((pantalla.width - ventana.width) / 2,
                (pantalla.height - ventana.height) / 2);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        arrendamientoPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("arrendamientoPU").createEntityManager();
        facturaQuery = java.beans.Beans.isDesignTime() ? null : arrendamientoPUEntityManager.createQuery("SELECT f FROM Factura f where f.pagada=-1");
        facturaList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : facturaQuery.getResultList();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox<Factura>();
        jFormattedTextField1 = new javax.swing.JFormattedTextField();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Crear Nuevo Cobro");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("Fecha: ");

        jLabel2.setText("Importe:");

        jLabel3.setText("Selecionar Factura:");

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, facturaList, jComboBox1);
        bindingGroup.addBinding(jComboBoxBinding);

        jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("d/MM/yyyy"))));

        jButton1.setText("Crear Nuevo Cobro");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel2)
                                .addComponent(jLabel1))
                            .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(37, 37, 37)
                                .addComponent(jLabel3))
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(33, 33, 33))))
            .addGroup(layout.createSequentialGroup()
                .addGap(187, 187, 187)
                .addComponent(jButton1)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(61, 61, 61)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addComponent(jButton1)
                .addContainerGap(24, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            Cobros c = new Cobros();
            String fecha = this.jFormattedTextField1.getText();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date d = sdf.parse(fecha);
            c.setFecha(d);
            c.setImporte(Float.parseFloat(this.jTextField1.getText()));
            c.setNumeroFactura((Factura) this.jComboBox1.getSelectedItem());
            System.out.println(this.jComboBox1.getSelectedItem().toString());
            Factura fact = c.getNumeroFactura();
            GuardarActualizarCobro(c, fact);
        } catch (ParseException ex) {
            Logger.getLogger(crearCobro.class.getName()).log(Level.SEVERE, "conversion Fecha Erronea", ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        this.arrendamientoPUEntityManager.close();
    }//GEN-LAST:event_formWindowClosing

    public void GuardarActualizarCobro(Cobros c, Factura f) {
        this.arrendamientoPUEntityManager.getTransaction().begin();
        this.arrendamientoPUEntityManager.persist(c);
        //System.out.println("factura a actualizar: " + f.getId());
        if (f != null) {
            f.getCobrosList().add(c);
            System.out.println("Restante por pagar: " + f.restantePorPagar());
            if (f.restantePorPagar() == 0.0) {
                System.out.println("Pagando factura");
                f.pagarFactura();
                System.out.println(f.toString() + "  " + f.getCobrosList().size());
                this.arrendamientoPUEntityManager.merge(f);
                this.arrendamientoPUEntityManager.flush();
                System.out.println("Revision restante por Pagar 1:" + f.restantePorPagar());
            } else {
                System.out.println("Añadiendo cobro");
                this.arrendamientoPUEntityManager.merge(f);
                this.arrendamientoPUEntityManager.flush();
                System.out.println("Revision restante por Pagar 2:" + f.restantePorPagar());
            }
        }
        this.arrendamientoPUEntityManager.getTransaction().commit();
        System.out.println("Guardadado y Actualizado correctamente");
    }

    /*
     * public void actualizarFactura(Factura f) { System.out.println("1a");
     * this.arrendamientoPUEntityManager.getTransaction().begin(); boolean
     * rollbackOnly =
     * this.arrendamientoPUEntityManager.getTransaction().getRollbackOnly();
     * System.out.println(this.arrendamientoPUEntityManager.isOpen()); Factura
     * fc = this.arrendamientoPUEntityManager.find(Factura.class, f);
     * System.out.println("1b"); this.arrendamientoPUEntityManager.merge(fc);
     * System.out.println("1c"); this.arrendamientoPUEntityManager.flush();
     * System.out.println("1d");
     * this.arrendamientoPUEntityManager.getTransaction().commit();
     * System.out.println("1e"); this.arrendamientoPUEntityManager.close();
     * System.out.println("Factura " + f.getId() + " Actualizada
     * correctamente"); }
     */
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(crearCobro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(crearCobro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(crearCobro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(crearCobro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new crearCobro().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager arrendamientoPUEntityManager;
    private java.util.List<persistencia.Factura> facturaList;
    private javax.persistence.Query facturaQuery;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox<Factura> jComboBox1;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTextField1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
